#include <mysql/mysql.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DB_HOST "localhost"
#define DB_USER "user"
#define DB_PASSWORD "password"
#define DB_NAME "todo_db"

// 初始化数据库连接
MYSQL* init_connection() {
    MYSQL *conn = mysql_init(NULL);
    if (conn == NULL) {
        fprintf(stderr, "mysql_init() failed\n");
        return NULL;
    }

    if (mysql_real_connect(conn, DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, 0, NULL, 0) == NULL) {
        fprintf(stderr, "mysql_real_connect() failed: %s\n", mysql_error(conn));
        mysql_close(conn);
        return NULL;
    }

    return conn;
}

// 添加任务
void add_task(MYSQL *conn, const char *task_name) {
    char query[512];
    snprintf(query, sizeof(query), "INSERT INTO tasks (task_name) VALUES ('%s')", task_name);

    if (mysql_query(conn, query)) {
        fprintf(stderr, "INSERT failed: %s\n", mysql_error(conn));
    } else {
        printf("Task added successfully!\n");
    }
}

// 显示所有任务
void show_tasks(MYSQL *conn) {
    if (mysql_query(conn, "SELECT * FROM tasks")) {
        fprintf(stderr, "SELECT failed: %s\n", mysql_error(conn));
        return;
    }

    MYSQL_RES *res = mysql_store_result(conn);
    if (res == NULL) {
        fprintf(stderr, "mysql_store_result() failed\n");
        return;
    }

    printf("\n=== Tasks ===\n");
    MYSQL_ROW row;
    while ((row = mysql_fetch_row(res))) {
        printf("[%s] %s (%s)\n", 
               row[2] ? "X" : " ", 
               row[1], 
               row[3]);
    }
    printf("=============\n\n");

    mysql_free_result(res);
}

// 更新任务状态
void update_task(MYSQL *conn, int task_id, int completed) {
    char query[256];
    snprintf(query, sizeof(query), "UPDATE tasks SET completed = %d WHERE id = %d", completed, task_id);

    if (mysql_query(conn, query)) {
        fprintf(stderr, "UPDATE failed: %s\n", mysql_error(conn));
    } else {
        printf("Task updated successfully!\n");
    }
}

// 删除任务
void delete_task(MYSQL *conn, int task_id) {
    char query[256];
    snprintf(query, sizeof(query), "DELETE FROM tasks WHERE id = %d", task_id);

    if (mysql_query(conn, query)) {
        fprintf(stderr, "DELETE failed: %s\n", mysql_error(conn));
    } else {
        printf("Task deleted successfully!\n");
    }
}

// 事务示例：批量添加任务
void batch_add_tasks(MYSQL *conn) {
    // 开始事务
    if (mysql_query(conn, "START TRANSACTION")) {
        fprintf(stderr, "START TRANSACTION failed: %s\n", mysql_error(conn));
        return;
    }

    // 添加多个任务
    if (mysql_query(conn, "INSERT INTO tasks (task_name) VALUES ('Task 1')")) {
        fprintf(stderr, "INSERT failed: %s\n", mysql_error(conn));
        mysql_query(conn, "ROLLBACK");
        return;
    }

    if (mysql_query(conn, "INSERT INTO tasks (task_name) VALUES ('Task 2')")) {
        fprintf(stderr, "INSERT failed: %s\n", mysql_error(conn));
        mysql_query(conn, "ROLLBACK");
        return;
    }

    // 提交事务
    if (mysql_query(conn, "COMMIT")) {
        fprintf(stderr, "COMMIT failed: %s\n", mysql_error(conn));
        return;
    }

    printf("Batch insert completed successfully!\n");
}

int main() {
    MYSQL *conn = init_connection();
    if (conn == NULL) {
        return 1;
    }

    int choice, task_id, completed;
    char task_name[256];

    while (1) {
        printf("1. Add Task\n");
        printf("2. Show Tasks\n");
        printf("3. Update Task\n");
        printf("4. Delete Task\n");
        printf("5. Batch Add Tasks (Transaction)\n");
        printf("6. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
        getchar(); // 消耗换行符

        switch (choice) {
            case 1:
                printf("Enter task name: ");
                fgets(task_name, sizeof(task_name), stdin);
                task_name[strcspn(task_name, "\n")] = 0; // 去除换行符
                add_task(conn, task_name);
                break;
            case 2:
                show_tasks(conn);
                break;
            case 3:
                printf("Enter task ID: ");
                scanf("%d", &task_id);
                printf("Enter 1 for completed, 0 for incomplete: ");
                scanf("%d", &completed);
                update_task(conn, task_id, completed);
                break;
            case 4:
                printf("Enter task ID: ");
                scanf("%d", &task_id);
                delete_task(conn, task_id);
                break;
            case 5:
                batch_add_tasks(conn);
                break;
            case 6:
                printf("Exiting...\n");
                goto exit;
            default:
                printf("Invalid choice!\n");
        }
    }

exit:
    mysql_close(conn);
    return 0;
}
    